// package 数据结构转换
package conversion

import (
	"encoding/json"
	"osiris/dto"
	"osiris/logger"
	"osiris/model"
)

func toDataMapJson(dataMap map[string]string) string {
	if dataMap == nil {
		return "nil"
	}

	dataMapJsonBytes, err := json.Marshal(dataMap)
	if err != nil {
		logger.Error(map[string]interface{}{"[core] [To datamap json] Data map serialization": err})
		return "nil"
	} else {
		return string(dataMapJsonBytes)
	}
}

func fromDataMapJson(dataMapJson string) map[string]string {
	if dataMapJson == "" || dataMapJson == "nil" {
		return make(map[string]string)
	}

	var dataMap map[string]string
	err := json.Unmarshal([]byte(dataMapJson), &dataMap)
	if err != nil {
		logger.Error(map[string]interface{}{"[core] [From datamap json] Data map unserialization": err})
		return make(map[string]string)
	}
	return dataMap
}

func HeaderDto2Model(header dto.BlockHeader) model.BlockHeaderModel {
	return model.BlockHeaderModel{
		Timestamp:        header.Timestamp,
		ChainID:          header.ChainID,
		Height:           header.Height,
		PreBlockHash:     header.PreBlockHash,
		HeaderHash:       header.HeaderHash,
		AccountStateHash: header.AccountStateHash,
		PeerStateHash:    header.PeerStateHash,
		TxHash:           header.TxHash,
		ReceiptHash:      header.ReceiptHash,
		GasUsed:          header.GasUsed,
		GasLimit:         header.GasLimit,
		ExtraDataJson:    toDataMapJson(header.ExtraData),
	}
}

func HeaderModel2Dto(header model.BlockHeaderModel) dto.BlockHeader {
	return dto.BlockHeader{
		Timestamp:        header.Timestamp,
		ChainID:          header.ChainID,
		Height:           header.Height,
		PreBlockHash:     header.PreBlockHash,
		HeaderHash:       header.HeaderHash,
		AccountStateHash: header.AccountStateHash,
		PeerStateHash:    header.PeerStateHash,
		TxHash:           header.TxHash,
		ReceiptHash:      header.ReceiptHash,
		GasUsed:          header.GasUsed,
		GasLimit:         header.GasLimit,
		ExtraData:        fromDataMapJson(header.ExtraDataJson),
	}
}
